<?php
class Mcountvisit extends CI_Model{
    public function __construct(){
        parent::__construct();
        $this->load->database();
    }

    public function checkAddressVisit ($ip){
        $time = time();
        $this->db->where('cv_IP', $ip);
        $this->db->where('cv_Time > ', $time - 3600); //set có 3600 giây là vitsit 1 lần
        $query = $this->db->get('countvisit');
            if($query->num_rows >= 1)
            {
                return true;
            }
        return false;
    }

    public function insertIPAccess($ip, $datetime, $time){
        $today = getdate();
        $data = array(
           'cv_IP' => $ip,
           'cv_DateTime' => $datetime,
           'cv_Time' => $time,
           'cv_Month' =>$today['mon'],
           'cv_Year' =>$today['year'],
           'cv_Day' =>$today['mday'] 
        );
        $this->db->insert('countvisit', $data);
    }

    public function countVisitALL() {
        $count = $this->db->count_all('countvisit');
        $global = $this->getGlobal();
        /*if($count > 1000) {
            $countVisitMonth =  $this->countVisitMonth();
            $data = array(
                'gl_CountVisitCurrent' => $global->gl_CountVisitCurrent + $count,
                'gl_CountOfMonth' => $countVisitMonth,
            );

            $this->updateCountVisit($data);
            $this->db->empty_table('countvisit');
        }
        
        return $global->gl_CountVisitCurrent + $count;*/
        return $count;

    }

    public function countVisitMonth() {
        $global = $this->getGlobal();
        $today = getdate();
        $this->db->from('countvisit');
        $this->db->where('cv_Month = ', $today['mon']);
        $this->db->where('cv_Year = ', $today['year']);

        //return $this->db->count_all_results() + $global->gl_CountOfMonth;
        return $this->db->count_all_results();
    }

    public function countVisitToDay() {
        $global = $this->getGlobal();
        $today = getdate();
        $this->db->from('countvisit');
        $this->db->where('cv_Month = ', $today['mon']);
        $this->db->where('cv_Year = ', $today['year']);
        $this->db->where('cv_Day = ', $today['mday']);

        return $this->db->count_all_results();   
    }

    public function updateCountVisit ($data) {
        $this->db->where('gl_Id', 1);
        $this->db->update('global', $data); 
    }

    public function getGlobal() {

        $this->db->select('*');
        $this->db->from('global');
        $this->db->where('gl_Id', 1);
        $query = $this->db->get();
        $data = $query->row();
        return $data;
    }
}